import axios from 'axios';

const http = axios.create({
    // 设置超时时间
    timeout: 10000,
    baseURL: process.env.NODE_ENV === "development" ? '/api' : `${window.location.origin}/`,
    // 其他axios的配置详见：https://www.kancloud.cn/yunye/axios/234845

});

// 添加请求拦截器
http.interceptors.request.use(
    config => {
        config.headers['token'] = `${window.sessionStorage.getItem('token')}`;
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

//响应拦截器
http.interceptors.response.use(
    response => {
        console.log(response)
        const res = response.data;

        if (res.code === 10401) { //没有登录
            setTimeout(()=>{
                window.location.href = window.location.origin + window.location.pathname;
            },1000)
            return Promise.reject(new Error(res.message || res));
        } else if (res.code !== 20000) {
            return Promise.reject(new Error(res.message || res))
        } else {
            return res.data
        }
    },
    error => {
        return Promise.reject(error);
    }
);

export default http;
